package org.linlinjava.litemall.core.util;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/***
 * @ClassName: ImageUploadUtil
 * @Description: TODO
 * @Author: fengyong
 * @DATE: 2020/7/25 11:39
 * @Verdion: 1.0
 */
public class ImageUploadUtil {


    /**
     * 图片上传
     * @param imgStr
     * @param storageClient
     * @return
     * @throws IOException
     */
    public static String imageUplad(String imgStr, FastFileStorageClient storageClient, String fileName) throws IOException {
        ByteArrayInputStream in = null;
        try {
            String imgSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            String imgFileName = System.currentTimeMillis() + "" + Math.round(Math.random() * 100) + "." + imgSuffix;
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] buffer = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < buffer.length; ++i) {
                if (buffer[i] < 0) {
                    //调整异常数据
                    buffer[i] += 256;
                }
            }
            in = new ByteArrayInputStream(buffer);
            StorePath storePath = storageClient.uploadImageAndCrtThumbImage(in, in.available(), FilenameUtils.getExtension(imgFileName), null);
            return storePath.getFullPath();
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    public static String imageUploadByFile(MultipartFile file, FastFileStorageClient storageClient) throws IOException {
        BASE64Encoder encoder = new BASE64Encoder();
        return imageUplad(encoder.encode(file.getBytes()), storageClient, file.getOriginalFilename());
    }
}
